<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 80%; margin-left: 50px">
      <el-form-item label="目录" prop="directoryId">
        <el-cascader v-model="temp.directoryId" :options="treeList" :props="treeProps" :show-all-levels="false" label="name" :check-strictly="true" clearable style="width: 100%" @change="choseMu" />
      </el-form-item>

      <el-form-item label="文件" prop="fileName">
        <el-upload class="upload-demo" :on-success="handleChange" :headers="headers" drag :action="upUrl" multiple accept=".pdf, .doc, .docx" :file-list="fileList">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>

        <!--        <el-upload class="upload-demo" drag :before-upload="beforeAvatarUpload" :on-success="handleChange" :action="upUrl"-->
        <!--          :limit="1" multiple style="width: 100%;" accept=".pdf, .doc, .docx" :file-list="fileList">-->
        <!--          <el-icon class="el-icon&#45;&#45;upload"></el-icon>-->
        <!--          <div class="el-upload__text">-->
        <!--            点击或者文件拖拽到这里上传-->
        <!--          </div>-->
        <!--          <span>上传文件只能是 pdf、doc、docx格式</span>-->
        <!--        </el-upload>-->
      </el-form-item>

      <el-form-item label="标准名称" prop="name">
        <el-input v-model="temp.name" />
      </el-form-item>

      <el-form-item label="标准版本号" prop="version">
        <el-input v-model="temp.version" />
      </el-form-item>

      <el-form-item label="标准发布时间" prop="releaseTime">
        <!-- <el-input v-model="temp.releaseTime" /> -->
        <el-date-picker v-model="temp.releaseTime" type="date" placeholder="选择日期" />
      </el-form-item>

      <el-form-item label="标准启用时间" prop="enableTime">
        <!-- <el-input v-model="temp.enableTime" /> -->
        <el-date-picker v-model="temp.enableTime" type="date" placeholder="选择日期" />
      </el-form-item>

      <el-form-item label="发布机构" prop="releaseInstitution">
        <el-input v-model="temp.releaseInstitution" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">
        {{ $t('table.cancel') }}
      </el-button>
      <el-button type="primary" :loading="loading" @click="dialogStatus === 'create' ? createData() : updateData()">
        {{ $t('table.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import { createGovernanceNorms, updateGovernanceNorms, getGovernanceNorms, upFile } from '@/api/standardsystem/governanceNorms'
export default {
  name: 'GovernanceNormsForm',
  data() {
    return {
      rules: {
        directoryId: [{ required: true, message: '目录为必填项', trigger: 'blur' }],
        name: [{ required: true, message: '标准名称为必填项', trigger: 'blur' }],
        version: [{ required: true, message: '标准版本号为必填项', trigger: 'blur' }],
        fileName: [{ required: true, message: '文件为必填项', trigger: 'blur' }],
        releaseTime: [{ required: true, message: '标准发布时间为必填项', trigger: 'blur' }],
        enableTime: [{ required: true, message: '标准启用时间为必填项', trigger: 'blur' }],
      },
      temp: {
        ancestralId: '1',
      },
      treeList: [],
      treeProps: {
        value: 'id',
        label: 'name',
        expandTrigger: 'hover',
        checkStrictly: true,
      },
      textMap: {
        update: '编辑',
        create: '新建',
      },
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      upUrl: process.env.VUE_APP_BASE_API + '/system/standardsystem/GovernanceNorms/upload',
      fileList: [],
      headers: {
        access_token: getToken(),
      },
    }
  },
  methods: {
    handleChange(data) {
      // alert("handleChange")

      if (data.code == 200) {
        this.fileList = []
        this.fileList.push({
          name: data.data.fileName, // 通过接口获取的文件名称
          url: '', // 文件的URL，如果有的话
        })
        this.temp.fileName = data.data.fileName
        this.temp.bucketName = data.data.bucketName
      }
    },
    // 资质照片上传前校验
    beforeAvatarUpload(file) {
      // alert("beforeAvatarUpload")
      // this.fileList = [];
      // return true;
      // const isPic = file.type.indexOf('image') >= 0;
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isPic) {
      //   this.$message.error('资质照片只能为图片格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!');
      // }
      // return isPic && isLt2M;
    },
    // 上传图片方法
    uploadImage(param) {
      const formData = new FormData()
      formData.append('file', param.file)

      upFile(param.file)
        .then((response) => {
          console.log('上传图片成功')
        })
        .catch((response) => {
          console.log('图片上传失败')
        })
    },
    choseMu(e) {
      this.temp.directoryId = e[e.length - 1]
      console.log(this.temp.directoryId)
    },
    setList(treeList) {
      this.treeList = treeList
    },
    getList() {
      this.$emit('refreshList')
    },
    resetTemp() {
      this.loading = false
      this.temp = {
        id: undefined,
        name: undefined,
        version: undefined,
        releaseTime: undefined,
        enableTime: undefined,
        releaseInstitution: undefined,
        releaseStatus: undefined,
        description: undefined,
        fileName: undefined,
        filePath: undefined,
        fileSize: undefined,
        createTime: undefined,
        updateTime: undefined,
        delFlag: undefined,
        directoryId: undefined,
        bucketName: undefined,
        ancestralId: '1',
      }
    },
    handleCreate() {
      this.fileList = []
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    chaneDate(datetime) {
      function addDateZero(num) {
        return num < 10 ? '0' + num : num
      }
      const d = new Date(datetime)
      const formatdatetime = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate())
      return formatdatetime
    },
    createData() {
      this.temp.releaseTime = this.chaneDate(this.temp.releaseTime)
      this.temp.enableTime = this.chaneDate(this.temp.enableTime)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          createGovernanceNorms(this.temp).then((response) => {
            this.loading = false
            if (response.data.code === 0) {
              this.getList()
              this.dialogFormVisible = false
              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
    },
    handleUpdate(id) {
      this.fileList = []
      this.resetTemp()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      getGovernanceNorms(id).then((response) => {
        if (response.data.code == 200) {
          this.temp = response.data.data
          console.log('获取配置信息=' + JSON.stringify(response.data.data))
          this.fileList.push({
            name: response.data.data.fileName, // 通过接口获取的文件名称
            url: '', // 文件的URL，如果有的话
          })
        } else {
          this.dialogFormVisible = false
          this.$message.error(response.data.msg)
        }
      })
    },
    updateData() {
      console.log('当前即将更改的内容=' + JSON.stringify(this.temp))
      this.temp.releaseTime = this.chaneDate(this.temp.releaseTime)
      this.temp.enableTime = this.chaneDate(this.temp.enableTime)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.directory_id !== undefined && this.temp.directory_id !== '' && this.temp.directory_id instanceof Array) {
            this.temp.directory_id = this.temp.directory_id[this.temp.directory_id.length - 1]
          }

          this.loading = true
          this.temp.stime = this.temp.releaseTime
          this.temp.etime = this.temp.enableTime
          updateGovernanceNorms(this.temp).then((response) => {
            this.loading = false
            if (response.data.code === 0) {
              this.dialogFormVisible = false
              this.getList()
              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
    },
  },
}
</script>
<style>
.el-upload {
  width: 100%;
}
.el-upload-dragger {
  width: 100%;
}
</style>
